<?php
namespace app\admin\common;
use app\admin\common\Base;
use think\Db;
use think\Loader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
//Order表的公共方法
class Order extends Base
{
    //定义公共方法-order表-列表
    public  function order_index($data,$o_type){
    	$this->assign('o_type', $o_type);//订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
    	//销售人员
        $this->get_staff_list();
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = [];
            $mapOr=[];
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }
            $map['dj_time']=['between',[$month['month_start'],$month['month_end']]];//按时间查询
            !isset($data['keyword']) || $data['keyword'] == '' ?  $map=$map:$map['sn|mark']=['like', '%'.trim($data['keyword']).'%']; //关键字（单号,备注）
            if(!isset($data['keyword']) || $data['keyword'] == ''){

            }else{
                $c = Db::name('customer')->where('name', 'like','%'.trim($data['keyword']).'%')->select();
                if(!empty($c)){
                    $c['ids'] = implode(',', array_column($c, 'id'));
                    $mapOr['user_id']=['in',  $c['ids']]; //供应商 
                }
            }
            if(!isset($data['state_id']) || $data['state_id'] == ''){//审核状态
            }else{
                 switch ($data['state_id']) {
                    case  0:
                       $map['status']=['eq',0];
                       break;
                    case  1:
                       $map['status']=['eq',1];
                       break;
                   
                   default:
                       break;
               }
            }
            !isset($data['dd_status']) || $data['dd_status'] == '' ?  $map=$map:$map['dd_status']=['in', $data['dd_status']]; //对单状态

            if(isset($data['by_admin']) && $data['by_admin'] != ''){//销售人员
                //halt($data['by_admin']);
                $data['by_admin'] = explode(',',$data['by_admin']);
                
                $map['by_admin']=['in', $data['by_admin']];
            }
            //halt($map);
            $volist = Db::name('order')->where($map)->whereOr($mapOr)->where('o_type', $o_type)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
            $count = Db::name('order')->where($map)->where('o_type', $o_type)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();

            $vlist=$this->order_list($volist,$o_type);
            //halt($volist);
            $list=[];
            if(!isset($data['order_status']) || $data['order_status'] == ''){//订单状态
                if(isset($data['store_id']) && $data['store_id'] != ''){//仓库
                    foreach ($vlist as $key => $val) {

                         $store_id_arr = explode(',',$data['store_id']);
                         //halt($data['store_id']);
                        $resu=array_intersect($val['store_list'],$store_id_arr);
                        if ($resu) {
                            array_push($list, $val);
                        }
                    }
                }else{
                    $list=$vlist;
                }
            }else{
                $data['order_status'] = explode(",", $data['order_status']);
                foreach ($vlist as $key => $val) {
                    if(isset($data['store_id']) && $data['store_id'] != ''){//仓库
                        $store_id_arr = explode(',',$data['store_id']);
                        $resu=array_intersect($val['store_list'],$store_id_arr);
                        if ($resu) {
                           if(in_array($val['order_status'], $data['order_status'])){
                                array_push($list, $val);
                           }
                        }
                    }else{
                        if(in_array($val['order_status'], $data['order_status'])){
                            array_push($list, $val);
                        }
                    }
                }
            }

            if(!isset($data['pay_status_name']) || $data['pay_status_name'] == ''){//付款状态
                 $list=$vlist;
            }else{
                $data['pay_status_name'] = explode(",", $data['pay_status_name']);
                //halt($data['pay_status_name']);
                foreach ($vlist as $key => $val) {
                    if(in_array($val['pay_status_name'], $data['pay_status_name'])){
                        array_push($list, $val);
                    }
                }
            }

            if(isset($data['is_export']) && $data['is_export'] == 1){//如果是导出操作
                //return ['type'=>3,'list'=>$list,'o_type'=>$o_type];
                return $this->order_export($list,$o_type);
              
            }else{
               //return ['type'=>2,'list'=>$this->grid_data($list, $count, $page, $limit)];
               return $this->grid_data($list, $count, $page, $limit); 
            }
        }
        //return ['type'=>1];
        return $this->fetch();
    } 

    //定义公共方法-order表-对单与撤销对单
    public  function order_dd($data){
    	$status = 0;
        $msg = "操作失败";
        $ids = $data['ids'];
        $type = $data['type'];
        Db::startTrans(); // 启动事务
        $list = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->select();
        foreach ($list as $key => $info) {
            if ($info['xht_id'] == 0 && $info['xh_id'] == 0) {

            }else{
                $msg = "存在关联单据不能操作";
                Db::rollback(); // 回滚事务
                return ['status' => $status, 'msg' => $msg];
            }
        }
       
            if ($type == 1) {
                $update = [
                    'dd_status' => 1,
                    'updatetime' => time(),
                    'dd_time' => time(),
                    'dd_user' => $this->Userinfo['id'],
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
            }
            if ($type == 2) {
                $update = [
                    'dd_status' => 0,
                    'updatetime' => time(),
                    'dd_time' => 0,
                    'dd_user' => 0,
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
            }
            if ($result) {
                Db::commit(); // 提交事务
                $status = 1;
                $msg = "操作成功";
            }
      
        if ($status != 1) {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];

    }

    //定义公共方法-order表-编辑更新订单
    public  function order_update($data){
    	$status = 0;
        $msg = "操作失败";
        $post=$data;
        Db::startTrans();
        if(isset($data['edit'])&&$data['edit']==1){//编辑保存
                $result = $this->edit_order($data);
                if ($result) {
                    Db::commit(); // 提交事务  
                    $status = 1;
                    $msg = "更新成功";
                }
                if($status!=1){
                    Db::rollback();
                }
                return json(['status' => $status, 'msg' => $msg]);
        }
        return json(['status' => $status, 'msg' => $msg]);
    }   

    //定义公共方法-order表-删除订单
    public  function order_del($data){
    	$status = 0;
        $msg = "删除失败";
        // 启动事务
        Db::startTrans();
        $list = Db::name('order')->where('id','in',$data['ids'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->select();
        foreach ($list as $key => $info) {
            if ($info['xhdd_id'] != 0 || $info['xht_id'] != 0 || $info['xh_id'] != 0) {
                $msg = "存在关联单据不能删除"; 
                Db::rollback(); // 回滚事务
                return ['status' => $status, 'msg' => $msg];
            }
            if ($info['status'] == 1) {
                $msg = "已审核单据不能删除"; 
                Db::rollback(); // 回滚事务
                return ['status' => $status, 'msg' => $msg];
            }
           
        }
            $update = [
                'is_del' => 1,
                'updatetime' => time(),
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('order')->where('id','in',$data['ids'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
            //halt($result);
            if ($result) {
                unset($update['last_user']);
                $res = Db::name('order_good')->where('order_id','in',$data['ids'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
                //$res = Db::name('order_good')->where('order_id','in',$data['ids'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->setField('is_del', 1);
                if ($res) {

                    Db::commit(); // 提交事务
                    $status = 1;
                    $msg = "删除成功";
                }
            }
       
        if ($status != 1) {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }  

     //定义公共方法-order表-添加
    public  function order_add($data,$o_type){
        switch ($o_type) {
        	case 0:
        		$sn_name="XHDD";
        		break;
        	case 1:
        		$sn_name="XH";
        		break;
        	case 2:
        		$sn_name="XHT";
        		break;
        	case 3:
        		$sn_name="GHDD";
        		break;
        	case 4:
        		$sn_name="CG";
        		break;
        	case 5:
        		$sn_name="GHT";
        		break;
        		
        	default:
        		halt("参数错误");
        		break;
        }
        //订单单号XH20210813001
        $sn = osn($sn_name);

        // 选择单据start
        if (!isset($data['id_array'])) {
            $count_imgs = 0;
            $imgs = null;
        } else {
            $imgs_arr = explode(',', $data['id_array']);
            $count_imgs = count($imgs_arr);
            $imgs = $data['id_array'];
        }
        $this->assign('imgs', $imgs);
        $this->assign('count_imgs', $count_imgs);
        // 选择单据end

        //仓库
        $this->get_store_list();
        //销售人员
        $this->get_staff_list();
        $today = date('Y-m-d', time());
        $this->assign('today', $today);
        $this->assign('sn', $sn);
        $this->assign('admin', $this->Userinfo);
        $this->assign('o_type', $o_type);//订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
        return $this->fetch();
    } 


    //定义公共方法-order表-编辑1-1
    public  function order_edit($data,$o_type){

        // 选择单据start
        if (!isset($data['id_array'])) {
            $count_imgs = 0;
            $imgs = null;
        } else {
            $imgs_arr = explode(',', $data['id_array']);
            $count_imgs = count($imgs_arr);
            $imgs = $data['id_array'];
        }
        $this->assign('imgs', $imgs);
        $this->assign('count_imgs', $count_imgs);
        // 选择单据end
        switch ($o_type) {
                case 0:
                    $sn_name="XHDD";
                    break;
                case 1:
                    $sn_name="XH";
                    break;
                case 2:
                    $sn_name="XHT";
                    break;
                case 3:
                    $sn_name="GHDD";
                    break;
                case 4:
                    $sn_name="CG";
                    break;
                case 5:
                    $sn_name="GHT";
                    break;
                
                default:
                    halt("参数错误");
                    break;
        }
        
         //关联订单
        if(isset($data['pid'])&&$data['pid']!=0){
            //halt($data['pid']);
            //订单信息
            $info=$this->order_one($data['pid']);
            $data['id']=$info['id'];
            $this->assign('pid',$data['pid']);
            $info['sn']=osn($sn_name, 1);
            $info['dj_time']=date('Y-m-d');
        }else{
            $this->assign('pid',0);
            //订单信息
            $info=$this->order_one($data['id']);
        }


        if(isset($data['o_way'])){
           $this->assign('o_way',$data['o_way']);
        }else{
           $this->assign('o_way',-1); 
        }

         //复制订单
        if(isset($data['copy'])&&$data['copy']==1){
            $info['sn']=osn($sn_name, 1);
            $info['dj_time']=date('Y-m-d');
            //halt($info['sn']);
        }else{
            $data['copy']=0;
        }
        $this->assign('copy',$data['copy']);
        $this->assign('o_type', $o_type);//订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
        //仓库
        $this->get_store_list();
        //销售人员
        $this->get_staff_list();
        $this->assign('admin', $this->Userinfo);

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
	        $page = intval($page);
	        $limit = isset($data['rows']) ? $data['rows'] : 10;
	        $limit = intval($limit);
	        $start = $limit * ($page - 1);

	        $volist = Db::name('order_good')->where('order_id', $data['id'])->where('is_del', 0)->limit($start, $limit)->select();
	        $count = Db::name('order_good')->where('order_id', $data['id'])->where('is_del', 0)->count();
	        $list=$this->order_good_list($volist);
	        //少于5条则填充
	        if(5-$count>0){
	            for ($i=0; $i <5-$count ; $i++) { 
	                array_push($list, ['id'=>$count+$i+1]);
	            }
	        }
	        return $this->grid_data($list, $count, $page, $limit);
        }
        $this->assign('id',$data['id']);
        $this->assign('sn', $info['sn']);
        $this->assign('info', $info);
        
        return $this->fetch();
    } 

    //定义公共方法-order表-编辑1-2-新增提交
    //$o_type 订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
    public  function order_save($data,$o_type){
    	$status = 0;
        $editId = 0;
        $msg = "操作失败";
        //halt($data);
        $post = $data;
        Db::startTrans(); // 启动事务
        $movegood = $data['movegood'];
        unset($data['movegood']);
       
        if (isset($data['o_shenhe'])) {//直接审核
            unset($data['o_shenhe']);
        }
        $info = Db::name('order')->where('sn', $post['sn'])->find();
        if (!empty($info)) {
            $msg = "存在相同的单据号";
            Db::rollback(); // 回滚事务
            return ['status' => $status, 'msg' => $msg];
        }
        //关联单-a
        $data=$this->gl_order_a($post,$data,$o_type);

        unset($data['accountdata']); //多账户
 
        //凭证
        if (isset($data['imgs'])&&$data['imgs']!='') {
            $imgs_arr= explode("," , $data['imgs']);
            for ($i=0; $i <count($imgs_arr) ; $i++) { 
                $up_imgs=[
                    'updatetime'=>time(),
                    'is_dj'=>1
                ];
                $r=Db::name('upload_img')->where('id',$imgs_arr[$i])->update($up_imgs);
                if(!$r){
                    $msg = "凭证参数错误";
                    Db::rollback(); // 回滚事务
                    return ['status' => $status, 'msg' => $msg]; 
                }
            }
        }



        $data['addtime'] = time();
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['updatetime'] = time();
        $data['dj_time'] = strtotime($data['dj_time']);
        $data['add_user'] = $this->Userinfo['id'];
        $data['last_user'] = $this->Userinfo['id'];

        $data['type'] = 0;
        $data['o_type'] = $o_type; //订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
        if(in_array($o_type, [0,1,2])){
        	$big_type=0;//0销货，1购货
        	$user_category=0;
        }else if (in_array($o_type, [3,4,5])) {
        	$big_type=1;//0销货，1购货
        	$user_category=1;
        }
        $data['user_category'] = $user_category; //0客户，1经销商
        $data['big_type'] = $big_type; //0销货，1购货


        $insert_id = Db::name('order')->insertGetId($data);
       
        //halt($post);
        //更新账户表start
        if ($post['account'] == -1) {
            $account_record = $post;

            $account_record['o_type'] = $o_type; //0收款单 1付款单 2销售单；3销售退货单；4购货单；5购货退货单
            $account_record['pid'] = $insert_id; //父id
            $account_record['psn'] = $data['sn']; //父sn
            $account_record['enterprise_id'] = $this->EnterpriseId;
            //$post['psn']=$data['sn'];//父sn
            $k = add_account_record($account_record);
        } else {
            $account_record = $post;
            $account_record['accountdata'][0] = [
                'account_id' => $account_record['account'],
                'jine' => $account_record['payment']
            ];
            $account_record['o_type'] = $o_type; //0收款单 1付款单 2销售单；3销售退货单；4购货单；5购货退货单
            $account_record['pid'] = $insert_id; //父id
            $account_record['psn'] = $data['sn']; //父sn
            $account_record['enterprise_id'] = $this->EnterpriseId;
            //$post['psn']=$data['sn'];//父sn
            //halt($post);
            $k = add_account_record($account_record);
        }

        if ($k != 1) {
            $msg = "参数错误";
            Db::rollback(); // 回滚事务
            return ['status' => $status, 'msg' => $msg];
        }
        //更新账户表end
        //添加子表
        if ($insert_id) {
            //关联单-b
            $this->gl_order_b($post,$insert_id,$o_type);


            if (add_order_good($insert_id, $movegood, $this->EnterpriseId, $o_type)) {

                if(isset($post['o_shenhe'])&&$post['o_shenhe']==1){////审核
                   $r=$this->order_shenhe($insert_id,1,$o_type); 
                   if ($r['status']==1) {
                        Db::commit(); // 提交事务  
                        $status = 1;
                        $editId = $insert_id;
                        $msg = "添加成功";
                   }
                }else{
                    Db::commit(); // 提交事务  
                    $status = 1;
                    $msg = "添加成功";

                }
               
            }
        }
        if ($status != 1) {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg , 'editId' => $editId];
    }

    //关联订单-a   
    public  function gl_order_a($post,$data,$o_type){
        if (isset($data['pid'])) {
            unset($data['pid']);
        }
        if(isset($data['o_way'])){
            unset($data['o_way']);
        }

        switch ($o_type) {
            case 1:
                if (isset($post['pid'])&&$post['pid']!=0) {//销售订单->销售单
                    $o = Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->find();
                    if (!empty($o)) {
                        $data['xhdd_sn'] = $o['sn'];
                        $data['xhdd_id'] = $o['id'];
                    }
                }
                break;
            case 2:
                 if(isset($post['pid'])&&isset($post['o_way'])&&$post['o_way']==0){//销售订单-销售退货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        $data['xhdd_sn']=$o['sn'];
                        $data['xhdd_id']=$o['id'];
                    } 
                }

                if(isset($post['pid'])&&isset($post['o_way'])&&$post['o_way']==1){//销货单-销售退货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        $data['xh_sn']=$o['sn'];
                        $data['xh_id']=$o['id'];
                    }
                    if($o['xhdd_id']!=0){
                         $odd=Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->find();
                         if(!empty($odd)){
                            $data['xhdd_sn']=$odd['sn'];
                            $data['xhdd_id']=$odd['id'];
                        } 
                    } 
                }
                break;
            case 4:
                if (isset($post['pid'])&&$post['pid']!=0) {//购货订单->购货单
                    $o = Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->find();
                    if (!empty($o)) {
                        $data['xhdd_sn'] = $o['sn'];
                        $data['xhdd_id'] = $o['id'];
                    }
                }
                break;
            case 5:
                 if(isset($post['pid'])&&isset($post['o_way'])&&$post['o_way']==0){//购货订单-购货退货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        $data['xhdd_sn']=$o['sn'];
                        $data['xhdd_id']=$o['id'];
                    } 
                }

                if(isset($post['pid'])&&isset($post['o_way'])&&$post['o_way']==1){//购货单-购货退货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        $data['xh_sn']=$o['sn'];
                        $data['xh_id']=$o['id'];
                    }
                    if($o['xhdd_id']!=0){
                         $odd=Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->find();
                         if(!empty($odd)){
                            $data['xhdd_sn']=$odd['sn'];
                            $data['xhdd_id']=$odd['id'];
                        } 
                    } 
                }
                break;
            
            default:
                break;
        }
        return $data;

    }


    //关联订单-b   
    public  function gl_order_b($post,$insert_id,$o_type){
        switch ($o_type) {
            case 1:
                if (isset($post['pid'])&&$post['pid']!=0) {
                    $o = Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->find();
                    if (!empty($o)) {
                        Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->setField('xh_sn', $post['sn']);
                        Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->setField('xh_id', $insert_id);
                    }
                }
                break;
            case 2:
                if(isset($post['pid'])&&$post['pid']!=0&&isset($post['o_way'])&&$post['o_way']==0){//补关联单据-销货订单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_id',$insert_id);
                    }
                }
                if(isset($post['pid'])&&$post['pid']!=0&&isset($post['o_way'])&&$post['o_way']==1){//补关联单据-销货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_id',$insert_id);
                    }
                    if($o['xhdd_id']!=0){
                        $odd=Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->find();
                        if(!empty($odd)){
                            Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                            Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->setField('xht_id',$insert_id);
                        } 
                    } 
                }
                break;
            case 4:
                if (isset($post['pid'])&&$post['pid']!=0) {
                    $o = Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->find();
                    if (!empty($o)) {
                        Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->setField('xh_sn', $post['sn']);
                        Db::name('order')->where('id', $post['pid'])->where('is_del', 0)->setField('xh_id', $insert_id);
                    }
                }
                break;
            case 5:
                if(isset($post['pid'])&&$post['pid']!=0&&isset($post['o_way'])&&$post['o_way']==0){//补关联单据-销货订单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_id',$insert_id);
                    }
                }
                if(isset($post['pid'])&&$post['pid']!=0&&isset($post['o_way'])&&$post['o_way']==1){//补关联单据-销货单
                    $o=Db::name('order')->where('id',$post['pid'])->where('is_del',0)->find();
                    if(!empty($o)){
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                        Db::name('order')->where('id',$post['pid'])->where('is_del',0)->setField('xht_id',$insert_id);
                    }
                    if($o['xhdd_id']!=0){
                        $odd=Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->find();
                        if(!empty($odd)){
                            Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->setField('xht_sn',$post['sn']);
                            Db::name('order')->where('id',$o['xhdd_id'])->where('is_del',0)->setField('xht_id',$insert_id);
                        } 
                    } 
                }
                break;
            
            default:
                break;
        }
    }
    //定义公共方法-order表-审核与反审核
    //$type 1审核 2反审核
    //$o_type  订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
    public  function order_shenhe($ids,$type,$o_type){

        $status = 0;
        $msg = "操作失败";
        // $ids = $data['ids'];
        // $type = $data['type'];
        Db::startTrans(); // 启动事务
        $list = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->select();
        //halt($list);
       
       
            if ($type == 1) {
                $update = [
                    'status' => 1,
                    'updatetime' => time(),
                    'shenhe_time' => time(),
                    'shenhe_user' => $this->Userinfo['id'],
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
                if ($result) {
                   
                   
                    foreach ($list as $key => $info) {
                         //添加商品出入库记录
                        $record['pid'] = $info['id'];
                        $record['psn'] = $info['sn'];
                        $record['user_id'] = $info['user_id']; //客户(经销商)
                        $record['sn'] = osn('QTRK', 3);
                        $record['mark'] = $info['mark'];
                        $record['dj_time'] = date('y-m-d', $info['dj_time']);
                        $record['total_price'] = $info['before_yh_price']; //优惠前的金额


                        $record['enterprise_id'] = $info['enterprise_id'];
                        $record['add_user'] = $info['add_user'];
                        $record['shenhe_user'] = $info['shenhe_user'];
                        $record['shenhe_time'] = $info['shenhe_time'];
                        $record['status'] =1;


                        $record['gooddata'] = []; //优惠后的金额
                        $info_good = Db::name('order_good')->where('order_id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->select();
                        foreach ($info_good as $ke => $va) {
                            $record['gooddata'][$ke]['good_id'] = $va['good_id']; //商品
                            $record['gooddata'][$ke]['unit_id'] = $va['unit_id']; //单位
                            $record['gooddata'][$ke]['store_id'] = $va['store_id']; //仓库
                            $record['gooddata'][$ke]['number'] = $va['shuliang']; //数量
                            $record['gooddata'][$ke]['price'] = $va['price']; //单价
                            $record['gooddata'][$ke]['jine'] = $va['jine']; //金额
                            $record['gooddata'][$ke]['mark'] = $va['mark']; //备注
                            $record['gooddata'][$ke]['use_ck'] = $va['use_kc']; //可用库存
                        }

 						//$o_type  订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
                        if(in_array($o_type, [4,2])){//采购和销售退回
				        	$in_or_out=0;//0,入库，1出库
				        	$money_in_or_out=1;//0客户付款；1客户进款
				        }else if (in_array($o_type, [1,5])) {//销售和采购退回
				        	$in_or_out=1;//0,入库，1出库
				        	$money_in_or_out=0;//0客户付款；1客户进款
				        }
				        switch ($o_type) {
				        	case 1:
				        		$in_or_out_type=1;//销售单，销售退回单
				        		$money_in_or_out_type=0;// 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
				        		break;
				        	case 2:
				        		$in_or_out_type=1;//销售单，销售退回单
				        		$money_in_or_out_type=1;// 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
				        		break;
				        	case 4:
				        		$in_or_out_type=0;//采购单，采购退回单
				        		$money_in_or_out_type=2;// 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
				        		break;
				        	case 5:
				        		$in_or_out_type=0;//采购单，采购退回单
				        		$money_in_or_out_type=3;// 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
				        		break;
				        	
				        	default:
				        	    Db::rollback(); // 回滚事务
				        		halt("参数错误");
				        		break;
				        }
                        //$in_or_out 0,入库，1出库
                        //入库方式：0，采购入库；1，销售退货入库；2，调拨单入库；3，其它入库单入库；4，核销单入库（出库方式：0采购退货，1，销售，2调拨3其它4核销）
                        $res = $this->inset_stock_record($record, $in_or_out, 0, $pid = $info['id'], $info['sn']);
                        if ($res == 3) {
                            $status = 0;
                            $msg = "已审核过，不可审核";
                            Db::rollback(); // 回滚事务
                            return ['status' => $status, 'msg' => $msg];
                        }
                        if ($res == 2) {
                            $status = 0;
                            $msg = "存在相同的单据号";
                            Db::rollback(); // 回滚事务
                            return ['status' => $status, 'msg' => $msg];
                        } 


                        //添加客户资金流水
                        $user_money['system_price'] = $info['yh_price']; //应收金额-优惠后的价格
                        $user_money['user_price'] = $info['payment']; //实收金额
                        $user_money['user_id'] = $info['user_id']; //客户ID
                        $user_money['type'] = $money_in_or_out; //0客户付款；1客户进款
                        $user_money['o_way'] = $money_in_or_out_type; // 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
                        $user_money['psn'] = $info['sn'];
                        $user_money['pid'] = $info['id'];
                        $user_money['enterprise_id'] = $this->EnterpriseId;
                        $res1 = add_user_money($user_money);
                        if ($res1 == 0) {
                            $msg = "参数错误";
                        }
                        
                    }

                    if ($res == 1 && $res1 == 1) {
                        $status = 1;
                        $msg = "操作成功";
                    } else {
                        $status = 0;
                    }
                   
                }
            }
            if ($type == 2) {
                foreach ($list as $key => $info) {
                    if ($info['xht_id'] == 0 && $info['xh_id'] == 0) {

                    }else{
                        $msg = "存在关联单据不能操作"; 
                        Db::rollback(); // 回滚事务
                        return ['status' => $status, 'msg' => $msg];
                    }
                }
                $update = [
                    'status' => 0,
                    'updatetime' => time(),
                    'shenhe_time' => 0,
                    'shenhe_user' => 0,
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('order')->where('id','in', $ids)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
                if ($result) {
                    $upda = [
                        'is_del' => 1,
                        'updatetime' => time(),
                        'last_user' => $this->Userinfo['id'],
                    ];
                    $upda1 = [
                        'is_del' => 1,
                        'updatetime' => time(),
                    ];
                    foreach ($list as $key => $info) {
                        $re = Db::name('stock_record')->where('pid', $info['id'])->where('psn', $info['sn'])->where('is_del', 0)->find();
                        //删除商品出入库记录-主表
                        $res = Db::name('stock_record')->where('pid', $info['id'])->where('psn', $info['sn'])->where('is_del', 0)->update($upda);

                        if ($res) {
                            unset($upda['last_user']);

                            //删除商品出入库记录 -附表
                            $resu = Db::name('stock_record_good')->where('pid', $re['id'])->where('is_del', 0)->update($upda1);

                            //删除客户资金流水
                            $resu1 = del_user_money($upda1, $info);
                            if(!$resu||$resu1!=1){
                                $status = 0;
                                $msg = "操作失败"; 
                                Db::rollback(); // 回滚事务
                                return ['status' => $status, 'msg' => $msg];
                            }
                        }
                        if ($resu && $resu1 == 1) {
                            $status = 1;
                            $msg = "操作成功";
                        } 
                    }
                    
                }
            }
       
        if ($status == 1) {
            Db::commit(); // 提交事务
        } else {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    } 

     //订单导出
    public function order_export($volist,$o_type){
        $excel = new Excel();
        //设置表格标题
        $title=$this->get_order_export_title($o_type);
        //halt($volist);
        $arr_list=[];
        if(!empty($volist)){
            foreach ($volist as $key => $val) {
                $og_list = Db::name('order_good')->where('order_id',$val['id'])->where('is_del',0)->select();
                foreach ($og_list as $k => $v) {
                    $arr=$val;
                    $og=$this->order_good_one($v['id']);
                    //halt($og);
                    foreach ($og as $k1 => $v1) {
                       $arr[$k1]=$v1;
                    }
                    array_push($arr_list, $arr);
                }
               
                $hj_arr=$title;
                foreach ($hj_arr as $ke => $va) {
                    $hj_arr[$ke]='';
                }
                $hj_arr['sn']=$val['sn'];
                $hj_arr['good_sn']="合计";

                $hj_arr['shuliang']= array_sum(array_map(function($value){return $value['shuliang'];}, $og_list));//求二维数组某一项的和
                $hj_arr['zk_e']= array_sum(array_map(function($value){return $value['zk_e'];}, $og_list));//求二维数组某一项的和
                $hj_arr['jine']= array_sum(array_map(function($value){return $value['jine'];}, $og_list));//求二维数组某一项的和
                $hj_arr['tax_e']= array_sum(array_map(function($value){return $value['tax_e'];}, $og_list));//求二维数组某一项的和
                $hj_arr['total_price']= array_sum(array_map(function($value){return $value['total_price'];}, $og_list));//求二维数组某一项的和
                array_push($arr_list, $hj_arr);
            }  
        }
        
        //添加标题到数组头部
        array_unshift($arr_list,$title);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <4 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }
        $merge=[];
        $options=[];
       ////订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单];
        switch ($o_type) {
            case  0:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AP3','A5:AP5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"销货订单记录",
                    'max_zimu'=>"AP",
                    'number'=>'3',
                ];
                $excel_export_title="销售订单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            case  1:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AU3','A5:AU5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"销售单记录",
                    'max_zimu'=>"AU",
                    'number'=>'3',
                ];
                $excel_export_title="销售单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            case  2:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AV3','A5:AV5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"销售退货单记录",
                    'max_zimu'=>"AV",
                    'number'=>'3',
                ];
                $excel_export_title="销售退货单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            case  3:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AF3','A5:AF5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"购货订单记录",
                    'max_zimu'=>"AF",
                    'number'=>'3',
                ];
                $excel_export_title="采购订单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            case  4:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AM3','A5:AM5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"购货单记录",
                    'max_zimu'=>"AM",
                    'number'=>'3',
                ];
                $excel_export_title="采购单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            case  5:
                $merge=[//合并
                    'start'=>6,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'],
                    'keyword'=>'sn',
                ];
                $options=[
                    'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],//居中
                    'bold'=>['A1:AM3','A5:AM5'],//加粗
                    'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
                ];
                $title=[//标题
                    'title'=>"购货退货单记录",
                    'max_zimu'=>"AM",
                    'number'=>'3',
                ];
                $excel_export_title="采购退货单导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
                $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
                break;
            default:
                halt("参数错误");
                break;
        }
        exit();
    }
   
    //$type 0 采购 ，1销售
    public function get_order_export_title($o_type)
    {
        $title=[];
        if(in_array($o_type, [3,4,5])){
            $title = [
                'dj_time' => '订单日期',
                'sn' => '订单编号',
                'type_name' => '业务类别',
                'customer_name' => '供应商',
                'before_yh_price' => '购货金额',
                'yh_price'=>"优惠后金额",
                'payment'=>'已付款',
                'pay_status_name'=>'付款状态',
                'dd_status_name'=>'对单状态',
                'order_status'=>'订单状态',
                'jh_time'=>'交货日期',
                'add_user_name'=>'制单人',
                'shenhe_user_name'=>'审核人',
                'mark'=>'备注',
                'print_number'=>'打印次数',
                'yh_lv'=>'优惠率',
                'yh_e'=>'优惠金额',
                'account'=>'结算账户',
                'arrears'=>'本次欠款',
                'good_sn'=>'商品编号',
                'good_name'=>'商品名称',
                'good_model'=>'商品型号',
                'good_attribute'=>'属性',
                'good_code'=>'商品条码',
                'good_cate'=>'商品类别',
                'good_mark'=>'商品备注',
                'unit_name'=>'单位',
                'shuliang'=>'数量',
                'price'=>'购货单价',
                'zk_lv'=>'折扣率（%）',
                'zk_e'=>'折扣额',
                'jine'=>'金额',
                'tax_lv'=>'税率（%）',
                'tax_e'=>'税额',
                'hs_price'=>'含税单价',
                'total_price'=>'价税合计',
                'store_name'=>'仓库',
                'mark'=>'备注',
                'xht_sn'=>'关联购货退货单号',
                'xh_sn'=>'关联购货单号',
                'xhdd_sn'=>'关联购货订单号',
                'base_unit_name'=>'基本单位',
                'base_number'=>'基本单位数量',
            ]; 
        }else if(in_array($o_type, [0,1,2])){
            $title = [
                'dj_time' => '订单日期',
                'sn' => '订单编号',
                'xh_sn'=>'关联销货单号',
                'type_name' => '业务类别',
                'by_admin_name' => '销售人员',
                'customer_name' => '客户',
                'c_cate' => '客户类别',
                'c_sn' => '客户编码',
                'c_name' => '客户名称',
                'before_yh_price' => '销售金额',
                'yh_e'=>"优惠金额",
                'yh_price'=>"优惠后金额",
                'payment'=>'已收款',
                'pay_status_name'=>'收款状态',
                'dd_status_name'=>'对单状态',
                'order_status'=>'订单状态',
                'jh_time'=>'交货日期',
                'add_user_name'=>'制单人',
                'shenhe_user_name'=>'审核人',
                'last_user_name'=>'最后修改人',
                'updatetime'=>'最后修改时间',
                'mark'=>'备注',
                'print_number'=>'打印次数',
                'export'=>'快递单号',
                'yh_lv'=>'优惠率',
                'yh_e'=>'优惠金额',
                'account'=>'结算账户',
                'arrears'=>'本次欠款',
                'good_sn'=>'商品编号',
                'good_name'=>'商品名称',
                'good_model'=>'商品型号',
                'good_attribute'=>'属性',
                //''=>'物料编码',
                'good_code'=>'商品条码',
                'good_cate'=>'商品类别',
                'good_mark'=>'商品备注',
                'unit_name'=>'单位',
                'shuliang'=>'数量',
                'price'=>'销售单价',
                'good_cg_price'=>'预计采购价',
                'zk_lv'=>'折扣率（%）',
                'zk_e'=>'折扣额',
                'zk_zhe'=>'折扣(折)',
                'zk_price'=>'折后单价',
                'jine'=>'金额',
                'good_cost_price'=>'参考成本',
                'good_yg_ml'=>'预估毛利',
                'good_yg_mlv'=>'预估毛利率（%）',
                'tax_lv'=>'税率（%）',
                'tax_e'=>'税额',
                'hs_price'=>'含税单价',
                'total_price'=>'价税合计',
                'store_name'=>'仓库',
                'mark'=>'备注',
                'use_kc'=>'可用库存',
                'xhdd_sn'=>'关联销货订单号',
                'base_unit_name'=>'基本单位',
                'base_number'=>'基本单位数量',
            ];
        }
        switch ($o_type) {
                case  0:
                    unset($title['c_cate']);//删除客户类别
                    unset($title['c_sn']);//删除客户编码
                    unset($title['c_name']);//删除客户名称
                 
                    unset($title['payment']);//删除已收款
                    unset($title['pay_status_name']);//删除收款状态
                    unset($title['dd_status_name']);//删除对单状态

                    unset($title['last_user_name']);//删除最后修改人
                    unset($title['updatetime']);//删除最后修改时间
                    unset($title['yh_lv']);//删除优惠率
                    unset($title['yh_e']);//删除优惠金额
                    unset($title['account']);//删除结算账户
                    unset($title['arrears']);//删除本次欠款
                    unset($title['xhdd_sn']);//删除关联销货订单号
                   
                    break;
                case  1:

                    $title['dj_time']="单据日期";
                    $title['sn']="单据编号";
                    unset($title['good_cg_price']);;//删除预计采购价
                    unset($title['good_cost_price']);;//删除参考成本
                    unset($title['good_yg_ml']);;//删除预估毛利
                    unset($title['good_yg_mlv']);;//删除预估毛利率
                    unset($title['customer_name']);;//删除客户
                    unset($title['order_status']);//删除订单状态
                    unset($title['jh_time']);//删除交货日期
                    unset($title['xh_sn']);//删除关联购货单号
                    break;
                case  2:

                    $title['dj_time']="单据日期";
                    $title['sn']="单据编号";
                    $title['xh_sn']="原销货单号";
                    $title['payment']="已退款";
                    $title['pay_status_name']="退款状态";
                    unset($title['good_cg_price']);;//删除预计采购价
                    unset($title['good_cost_price']);;//删除参考成本
                    unset($title['good_yg_ml']);;//删除预估毛利
                    unset($title['good_yg_mlv']);;//删除预估毛利率
                    unset($title['customer_name']);;//删除客户
                    unset($title['order_status']);//删除订单状态
                    unset($title['jh_time']);//删除交货日期
                    break;
                case  3:
                    unset($title['yh_price']);//删除优惠后金额
                    unset($title['payment']);//删除已付款
                    unset($title['pay_status_name']);//删除付款状态
                    unset($title['dd_status_name']);//删除对单状态

                    unset($title['yh_lv']);//删除优惠率
                    unset($title['yh_e']);//删除优惠金额
                    unset($title['account']);//删除结算账户
                    unset($title['arrears']);//删除本次欠款

                    unset($title['xhdd_sn']);//删除关联购货订单号
                    unset($title['xh_sn']);//删除关联购货单号
                    unset($title['xht_sn']);//删除关联购货退货单号

                    break;
                case  4:
                    $title['dj_time']="单据日期";
                    $title['sn']="单据编号";
                    unset($title['order_status']);//删除订单状态
                    unset($title['jh_time']);//删除交货日期
                    unset($title['xh_sn']);//删除关联购货单号
                    break;
                case  5:
                    $title['dj_time']="单据日期";
                    $title['sn']="单据编号";
                    $title['payment']="已退款";
                    $title['pay_status_name']="退款状态";
                    unset($title['order_status']);//删除订单状态
                    unset($title['jh_time']);//删除交货日期
                    unset($title['xht_sn']);//删除关联购货退货单号
                    break;
                
                default:
                    halt("参数错误");
                    break;
        }
        return $title;
    }
}
